<template>
  <div class="operatStateBox board-border">
    <div class="warp">
      <NormalPie :pieData="pieData"></NormalPie>
      <div class="listBox">
        <div class="item" v-for="(item, index) in stateTimeLists">
          <div><span class="dot" :style="{ background: item.color }"></span></div>
          <div>
            <span>{{ item.name }}</span>
          </div>
          <div>
            <span> {{ item.value }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import moment from 'moment';
import api from '@api/api';
import { getRoleId } from '@/unit/tool';
// import { RepairType } from '@/unit/constantValue';
import NormalPie from '@components/echart/normalPie';
import { themeOption } from '@components/echart/buildEChartOption';
import '@assets/styles/publicStyle/index.less';

import { createNamespacedHelpers } from 'vuex';
const { mapState } = createNamespacedHelpers('board/');

// const pieColor = ['#c1cdc1', '#ef4848', '#ffc600', '#1cc824'];

const pieColor = ['#ef4848', '#c1cdc1', '#1cc824', '#ffc600'];

function buildPieData(pieDataLists, titleStr, subTitleStr) {
  let lists = [{ option: {}, data: [] }];
  let dataLists = [];
  let legendData = [];
  // 控制显示的项目数
  // let showCount = 10;

  pieDataLists.forEach((item, index) => {
    let { name, value, label } = item;
    dataLists.push({
      name,
      value,
      label,
    });
  });

  // dataLists = dataLists.sort((a, b) => {
  //   return a.value - b.value;
  // });
  // .slice(0, showCount);

  legendData = dataLists.map((item, index) => {
    let name = item.name == '' ? '未知字段' : item.name;
    return name;
  });

  lists[0].option = {
    // radius: ['55', '75'],
    radius: 60,
    clockwise: false,
    center: ['140', '113'],
    label: {
      position: 'outside',
      formatter: function(params) {
        // let newValue = Math.floor(e.percent * 100) / 100;
        // if (newValue >= 3) {
        //   return newValue + '%';
        // } else {
        //   return '';
        // }
        // debugger
        return `${params.name} ${params.percent}%`;
      },
    },
  };

  lists[0].data = dataLists;
  return {
    // title: {
    //   text: titleStr,
    //   left: '120',
    //   top: '96',
    //   textStyle: {
    //     fontSize: 18,
    //     fontWeight: 400,
    //     color: '#1890FF',
    //   },
    // },
    color: pieColor,
    tooltip: {
      // formatter: (params) => `<p>${params.marker}${params.name}&nbsp;${parseInt(moment.duration(params.value * 1000 * 60).asHours())}小时</p>`,
      formatter: (params) => {
        return `<p>${params.marker}${params.name}&nbsp;${params.data.label}</p>`;
      },
    },
    graphic: [],
    legend: {
      orient: 'vertical',
      left: '360',
      top: '80',
      icon: 'circle',
      // data: legendData,
      data: [],
      textStyle: {
        fontSize: 12,
        fontWeight: 200,
        color: '#FFFFFF',
      },
      formatter: (params) => {
        let str = '';
        dataLists.forEach((item, index) => {
          if (params == item.name) {
            // str = `${item.name} : ${parseInt(moment.duration(item.value * 1000 * 60).asHours())}小时`;
            str = `${item.name} : ${params.value}小时`;
          }
          return false;
        });

        return str;
      },
    },
    dataLists: lists,
  };
}

function formatStateTime(str) {
  switch (str) {
    case 'offline':
      return '离线';
    case 'running':
      return '运行';
    case 'alarm':
      return '报警';
    case 'stop':
      return '待机';
    default:
      break;
  }
}

export default {
  name: 'stateStatistics',
  components: {
    NormalPie,
  },
  props: {},
  data() {
    return {
      userName: '',
      name: '',
      role: '',
      compId: '',
      pieData: {},
      stateTimeLists: [],
      stateTimeTotal: '',
      // startTime: `${moment()
      //   .startOf('week')
      //   .format('YYYY-MM-DD')} 00:00:00`,
      // endTime: `${moment()
      //   .endOf('week')
      //   .format('YYYY-MM-DD')} 23:59:59`,
    };
  },
  watch: {
    timeSwich: function(newValue, oldValue) {
      let { startTime, endTime } = newValue;
      this.boardGetStateTime({ companyId: this.compId, startTime, endTime }, 'pieData', 'stateTimeLists', 'stateTimeTotal');
    },
  },
  computed: {
    ...mapState(['timeSwich']),
  },
  methods: {
    // 获取机床某时间段内的各个状态时间
    async boardGetStateTime(parames, key, listKey, totalKey) {
      const resData = await api.boardGetStateTime({ ...parames });
      let dataLists = [];
      let { alarm, offline, running, stop, totalStr } = resData;
      let _resData = {
        alarm,
        offline,
        running,
        stop,
      };
      for (const key in _resData) {
        if (Object.hasOwnProperty.call(_resData, key)) {
          let isKey = key.indexOf('Str') == -1;
          if (isKey) {
            dataLists.push({
              name: formatStateTime(key),
              value: _resData[key],
              label: resData[key + 'Str'],
            });
          }
        }
      }
      this[listKey] = dataLists.map((item, index) => {
        // total = total + item.value;
        return {
          name: item.name,
          // value: `${parseInt(moment.duration(item.value * 1000 * 60).asHours())}小时${moment.duration(item.value * 1000 * 60).minutes()}分`,
          value: item.label,
          color: pieColor[index],
        };
      });

      this[totalKey] = totalStr;
      this[key] = buildPieData(dataLists, this[totalKey], '时间统计');
    },
  },
  created() {},
  mounted() {
    getRoleId(this);
  },
};
</script>

<style scoped="scoped" lang="less">
@import './style.less';
</style>
